<template>

    <div class="app-container" v-if="canList">
        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="申请人名字"
                      v-model="listQuery.entity.user.name">
            </el-input>
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="申请人编号"
                      v-model="listQuery.entity.user.code">
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="订单号"
                      v-model="listQuery.entity.apply.orderNo">
            </el-input>
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item input"
                      placeholder="物流单号"
                      v-model="listQuery.entity.apply.logNo">
            </el-input>


            <el-select @change='handleFilter' clearable class="filter-item input" style="width: 130px"
                       v-model="listQuery.entity.apply.status"
                       placeholder="状态">
                <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item" :value="index">
                </el-option>
            </el-select>
            <el-date-picker
                    class="filter-item input"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    v-model="listQuery.entity.apply.dates"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="申请时间开始日期"
                    end-placeholder="申请时间结束日期">
            </el-date-picker>

            <div style="display: inline-block">

                <el-button style="margin-left: 10px;" class="filter-item" type="primary" v-waves icon="el-icon-search"
                           @click="handleFilter">查找
                </el-button>
<!--                <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"-->
<!--                           v-if="canSave" icon="el-icon-edit">添加-->
<!--                </el-button>-->
                <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download"
                           @click="handleDownload">导出
                </el-button>
            </div>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
                  style="width: 100%;">
            <el-table-column align="center" label="流水码">
                <template slot-scope="scope">
                    <span>{{scope.row.apply.id}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="订单号"  >
                <template slot-scope="scope">
                    <span style="color:red" v-if="scope.row.apply.status==3&&(new Date().getTime()-(new Date(scope.row.apply.date).getTime())>(10*1000*60*60*24))">{{scope.row.apply.orderNo}}</span>
                    <span v-else >{{scope.row.apply.orderNo}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="申请人">
                <template slot-scope="scope">
                    <span>{{scope.row.user.name}}-{{scope.row.user.code}}</span>
                </template>
            </el-table-column>

          <el-table-column align="center" label="申请单位">
            <template slot-scope="scope">
              <span>{{scope.row.apply.unit}}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" label="价格">
            <template slot-scope="scope">
              <span>{{scope.row.apply.price}}</span>
            </template>
          </el-table-column>


            <el-table-column align="center" label="物流单号">
                <template slot-scope="scope">
                    <span>{{scope.row.apply.logNo}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="总数">
                <template slot-scope="scope">
                    <span>{{scope.row.apply.amount}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="总价">
                <template slot-scope="scope">
                    <span>{{scope.row.apply.price}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="状态">
                <template slot-scope="scope">
                                                <span>

                         <el-tag :type="tagTypes[scope.row.apply.status]">     {{statusOptions[scope.row.apply.status]}}</el-tag>

                        </span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="申请时间">
                <template slot-scope="scope">
                    <span>{{parseTime(scope.row.apply.date)}}</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" v-if="canUpdate" size="mini" @click="handleUpdate(scope)">编辑</el-button>
                    <el-button v-if="canSave" size="mini" type="danger"
                               @click="handleDelete(scope)">删除
                    </el-button>
                </template>
            </el-table-column>

        </el-table>

        <div class="pagination-container" style="margin-top: 20px">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit"
                           layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px"
                     style='width: 450px; margin-left:50px;'>
                <el-form-item label="申请人名字" prop="userId">
                    <el-input :disabled="true" v-model="temp.user.name"></el-input>
                </el-form-item>
                <el-form-item label="申请人编号" prop="userId">
                    <el-input :disabled="true" v-model="temp.user.code"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input  type="textarea" v-model="temp.apply.remark"></el-input>
                </el-form-item>
                <el-form-item label="订单号" prop="orderNo">
                    <el-input v-model="temp.apply.orderNo"></el-input>
                </el-form-item>
                <el-form-item label="物流单号" prop="logNo">
                    <el-input v-model="temp.apply.logNo"></el-input>
                </el-form-item>
                <el-form-item label="总数" prop="amount">
                    <el-input disabled="true" v-model="temp.apply.amount"></el-input>
                </el-form-item>
                <el-form-item label="总价" prop="price">
                    <el-input disabled="true" v-model="temp.apply.price"></el-input>
                </el-form-item>
              <el-form-item label="地址" prop="price">
                <el-input type="textarea"  v-model="temp.apply.address"></el-input>
              </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select class="filter-item" v-model="temp.apply.status" placeholder="状态">
                        <el-option v-for="(item,index) in  statusOptions" :key="item" :label="item"
                                   :value="index">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="申请时间" prop="date">
                    <el-date-picker v-model="temp.apply.date" type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="申请时间">
                    </el-date-picker>
                </el-form-item>

                <el-card class="box-card">
                    <el-table border :data="temp.apply.items" fit>
                        <el-table-column align="center" label="产品">

                            <template slot-scope="scope">
                                <span>{{scope.row.goodsName}}</span>
                            </template>

                        </el-table-column>
                        <el-table-column
                                align="center"
                                label="数量">
                            <template slot-scope="scope">
                                <span>{{scope.row.number}}</span>
                            </template>
                        </el-table-column>

                        <el-table-column
                                align="center"
                                label="单价">
                            <template slot-scope="scope">
                                <span>{{scope.row.price}}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialogForm">取消</el-button>
                <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确认</el-button>
                <el-button v-else type="primary" @click="updateData">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<style type="stylus">
    .filter-container {
        /*padding-bottom: 20px;*/
    }

    .filter-item {
        margin-bottom: 10px;
    }

    .filter-item.input {
        /*line-height: 60px*/
        margin-right: 10px;
    }
</style>

<script>
    import {list,down, save, update, remove,info} from '@/api/goods_apply'
    import waves from '@/directive/waves' // 水波纹指令
    import {parseTime} from '@/utils'


    import {mapGetters} from 'vuex'
    import {hasAuth} from '@/utils/auth'
    import {downExcel} from "@/utils/down";

    export default {
        name: 'test',
        directives: {
            waves
        },
        data() {
            return {
                tableKey: 0,
                list: null,
                total: null,
                listLoading: true,
                date: null,
                listQuery: {
                    json:true,
                    page: 1,
                    limit: 20,
                    order: 'apply.id desc',
                    entity: {
                        user: {},
                        apply: {
                            userId: null,
                            remark: null,
                            orderNo: null,
                            logNo: null,
                            amount: null,
                            price: null,
                            adminId: null,
                            adminName: null,
                            date: null,
                            dates: null,
                            status: null
                        }
                    }
                },
                statusOptions: ["待审核", "通过", "拒绝","发货","已收货"],
                tagTypes: ['info', '', 'warning', 'danger', 'warning'],
                temp: {
                   apply:{
                       id: null,
                       userId: null,
                       remark: null,
                       unit: null,
                       address: null,
                       orderNo: null,
                       logNo: null,
                       date: null,
                       amount: null,
                       price: null,
                       status: null,
                       adminId: null,
                       adminName: null
                   },
                    user:{

                    }
                },
                dialogFormVisible: false,
                dialogStatus: '',
                textMap: {
                    update: '修改',
                    create: '新增'
                },
                rules: {
                    userId: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    remark: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    orderNo: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    logNo: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    date: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    amount: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    price: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    status: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'blur'
                    }],
                    adminId: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }],
                    adminName: [{
                        required: false,
                        message: '必填字段',
                        trigger: 'change'
                    }]
                },
                downloadLoading: false,
                qData: {
                    token: '',
                    key: ''
                }
            }
        },
        created() {
            this.getList()
        },
        computed: {
            ...mapGetters([
                'perms'
            ]),
            canSave() {
                return hasAuth(this.perms, 'goods:apply:save')
            },
            canDelete() {
                return hasAuth(this.perms, 'goods:apply:delete')
            },
            canUpdate() {
                return hasAuth(this.perms, 'goods:apply:update')
            },
            canList() {
                return hasAuth(this.perms, 'goods:apply:list')
            }
        },
        methods: {
            parseTime(time) {
                return parseTime(time, '{y}-{m}-{d}')
            },
            getList() {
                this.listLoading = true
                list(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                })
            },
            handleFilter() {
                this.listQuery.page = 1
                this.getList()
            },
            handleSizeChange(val) {
                this.listQuery.limit = val
                this.getList()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getList()
            },
            handleModifyStatus(row, status) {
                this.$message({
                    message: '操作成功',
                    type: 'success'
                })
                row.status = status
            },
            beforeFormShow(row) {
                this.resetTemp(row) // 更新数据
                // 存在图片

            },
            afterFormShow(row) {

            },
            beforeFormCommit() {
            },
            resetTemp(row) {

                this.temp = {}
                if (row) {
                    this.temp = JSON.parse(JSON.stringify(row)) // copy obj
                }

                info(this.temp.apply.id).then(res => {
                    this.temp.apply = res.data
                    this.temp.apply.items = res.extra.items
                })

            },
            handleCreate() {
                this.beforeFormShow()
                this.resetTemp()
                this.dialogStatus = 'create'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.afterFormShow()
                    this.$refs['dataForm'].clearValidate()
                })
            },
            handleDelete(scope) {
                this.index = scope.$index
                // this.beforeFormShow(scope.row)
                // this.temp = Object.assign({}, row) // copy obj
                this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$message({
                    //   type: 'success',
                    //   message: '删除成功!'
                    // })
                    this.deleteData()
                }).catch(() => {
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                })
            },
            createData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            save(this.temp).then(res => {
                                this.temp = res.data
                                this.list.unshift(this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            deleteData() {
                // const ids = [this.temp.id]
                const ids = [this.list[this.index].apply.id]
                remove({ids: ids}).then(res => {
                    // 从当前队列中移除
                    this.list.splice(this.index, 1)
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                })
            },
            handleUpdate(scope) {
                this.index = scope.$index
                this.beforeFormShow(scope.row)
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].clearValidate()
                })
            },
            updateData() {
                this.$refs['dataForm'].validate((valid) => {
                        if (valid) {
                            this.beforeFormCommit()
                            let params = this.temp.apply
                            update(params).then(() => {
                                this.list.splice(this.index, 1, this.temp)
                                this.closeDialogForm()
                                this.$notify({
                                    title: '成功',
                                    message: '更新成功',
                                    type: 'success',
                                    duration: 2000
                                })
                            })
                        }
                    }
                )
            },
            closeDialogForm() {
                this.dialogFormVisible = false
            },
          handleDownload() {
            this.downloadLoading = true
            down(this.listQuery).then(res => {
              downExcel(res)
              this.downloadLoading = false
              this.$notify({
                title: '成功',
                message: '下载成功',
                type: 'success',
                duration: 2000
              })
            })
          },
        }
    }
</script>
